// pages/controler/controler.js
import moment from "moment"
import request from "../../utils/request"
Page({

    /**
     * 页面的初始数据
     */
    data: {
        id:486194122,
        index:0,
        ids:[],
        songUrl:'',
        left:0,
        duration:"00:00",
        currentTime:"00:00",
        isplay:true,
        playType:'icon-suijibofang',
        songList:[],
        scrollBottom:-856,
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        console.log("options",options);
        this.setData({index:options.index-0,ids:JSON.parse(options.ids)})
        this.getsongList()
        this.initFn()
    },
    async initFn(){
        await this.getSongInfo()
        await this.getSongUrl()
        this.audioInit()
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    },
    /* 
    *   歌曲详情
    */
    async getSongInfo(){
        const {index,ids}=this.data
        let result=await request('/song/detail',{ids:ids[index]})
        this.setData({
            songInfo:result.songs[0],
            duration:moment(result.songs[0].dt).format('mm:ss')
        })
    },
    /* 
    *   歌曲播放地址
    */
   async getSongUrl(){
    const {index,ids}=this.data
    let result=await request('/song/url',{id:ids[index]})
    // console.log(result);
    this.setData({
        songUrl:result.data[0].url
    })
   },
   /* 
   *    实例背景音频管理器
   */
  audioInit(){
     this.audioManager=wx.getBackgroundAudioManager()
     this.audioManager.src=this.data.songUrl
     this.audioManager.title=this.data.songInfo.name
     
     this.audioManager.onTimeUpdate(()=>{
        //  this.audioManager.currentTime
        let left=(this.audioManager.currentTime/this.audioManager.duration)*640
        this.setData({
            left,
            // duration:moment(Math.floor(this.audioManager.duration*1000)).format('mm:ss'),
            currentTime:moment(Math.floor(this.audioManager.currentTime*1000)).format('mm:ss')
        })
     })
     this.audioManager.onEnded(()=>{
         if(this.data.playType==="icon-24gl-repeatOnce2"){
            this.audioManager.src=this.data.songUrl
            this.audioManager.title=this.data.songInfo.name
         }else{
             this.nextSong()
         }
     })
  },
  /* 
  *    播放暂停
  */
    playOrPause(){
        let paused=this.audioManager.paused
        if(paused){
            this.audioManager.play()
            this.setData({isplay:true,})
        }else{
            this.audioManager.pause()
            this.setData({isplay:false,})
        }
    },

    /* 
    *   上、下一曲
    */
   previous(){
        let index=this.data.index
        if(index===0){
            index=this.data.ids.length-1
        }else{
            index=index-1
        }
        this.setData({index,})
        this.initFn()
   },
   nextSong(){
        let {index,ids,playType}=this.data
        if(index===(ids.length-1)){
            index=0
        }else{
            index=index+1
        }
        if(playType==="icon-suijibofang"){
            index=Math.floor(Math.random()*ids.length);
        }
        this.setData({index,})
        this.initFn()
    },
    /* 
    *   改变播放状态
    */
   changePlayType(){
       const typeLis=['icon-24gl-repeatOnce2','icon-24gl-repeat2','icon-suijibofang']
       let {playType}=this.data
       let index=typeLis.indexOf(playType)
       if(index===2){
           index=0
       }else{
           index++
       }
       this.setData({playType:typeLis[index],})
   },
   /* 
   *    关闭/打开弹窗
   */
   closeLis(){
        this.setData({scrollBottom:-856})
   },
   openLis(){
        this.setData({scrollBottom:0})
   },
//    获取歌单列表
   getsongList(){
       let songList=wx.getStorageSync('songList')
       this.setData({songList,})
   },
    //    歌单列表点击播放
    goPlay(e){
        let index=e.currentTarget.dataset.index
        this.setData({index,})
        this.closeLis()
        this.initFn()
    },
  /* 
  * 秒数格式化为分钟
  */
  formatTime(seconds=0){
    if(isNaN(seconds-0)) return "--:--"
    let time=':'
    let min=Math.floor(seconds/60)+''
    if(min.length<2) min='0'+min
    let sec=Math.floor(seconds%60)+''
    if(sec.length<2) sec='0'+sec
    return min+time+sec
  },
  /* 
  * 下载
  */
 downloadFn(){
    const {songUrl,songInfo}=this.data
    const filePath=`${wx.env.USER_DATA_PATH}/${songInfo.name}.jpg`
    wx.downloadFile({
      url: songInfo.al.picUrl,
      filePath,
      success(res){
        wx.saveImageToPhotosAlbum({
            filePath: res.filePath,
            success(res){
                wx.showToast({
                    title:"保存成功"
                })
            }
        })
        
      },
      complete(res){
        console.log('接口调用结束',res);
      }
    })

 },
 getsaveFile(){
    const {songUrl,songInfo}=this.data
    const filePath=`${wx.env.USER_DATA_PATH}/${songInfo.name}.mp3`
    wx.downloadFile({
        url: songUrl,
        filePath,
        success(res){
            wx.showToast({
                title:"暂存成功"
            })
            console.log("暂存成功,前往'Android/data/com.tencent.mm/MicroMsg/wxanewfiles'查询保存");
        },
        fail(){
            wx.showToast({
                title:"保存失败",
                icon:"error"
            })
        }
   })  
 }
})